package com.verisette.ncos.service.card.bizunit;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.corp.agi.common.exception.ProcessException;
import org.corp.agi.service.bean.ProcessContext;
import org.corp.agi.service.bizunit.CommonBusinessUnit;

import com.verisette.ncos.common.ProjectConstant;
import com.verisette.ncos.persistence.domain.MasterMember;
import com.verisette.ncos.persistence.domain.TransCustomerOrder;
import com.verisette.ncos.web.card.bean.CardCreateBean;

public class SaveAllCardFileBU extends CommonBusinessUnit {
	private Logger logger = Logger.getLogger(SaveAllCardFileBU.class);
	
	@Override
	public void execute(ProcessContext processContext) throws ProcessException {
		if(logger.isInfoEnabled()) logger.info( this.getClass().getSimpleName() + ": execute" );
//		MasterUserProfile userBean = (MasterUserProfile) processContext.getUserBean();
		MasterMember member = null;
		TransCustomerOrder order = null;
		Object o = processContext.getValueObject();
		if(o instanceof CardCreateBean){
			CardCreateBean cardCreateBean = (CardCreateBean)o;
			member = cardCreateBean.getOrder().getMasterMember(); 
			order = cardCreateBean.getOrder();
		} else if(o instanceof TransCustomerOrder){
			order = (TransCustomerOrder)o;
			if(order!=null){
				member = order.getMasterMember();
			}
			CardCreateBean c = (CardCreateBean) processContext.getOriginalRequest().getValueObject();
			c.setOrder(order);
			o = c;
		}
		
		
		if(order!=null){
			File srcPDFFile = null;
			File destPDFFile = null;
			try{
				//card
				srcPDFFile = new File(ProjectConstant.APP_TEMP_PDF_FOLDER + "\\" + order.getPdfPath());
				destPDFFile = new File(ProjectConstant.APP_ORDER_PDF_FOLDER + "\\" + order.getPdfPath());
				FileUtils.moveFile(srcPDFFile, destPDFFile);
				
				//preview
				srcPDFFile = new File(ProjectConstant.APP_TEMP_PDF_PREVIEW_FOLDER + "\\" + order.getPdfPath());
				destPDFFile = new File(ProjectConstant.APP_ORDER_PDF_PREVIEW_FOLDER + "\\" + order.getPdfPath());
				FileUtils.moveFile(srcPDFFile, destPDFFile);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
		
		if(member!=null && member.getMmbPicturePath() != null && !"".equals(member.getMmbPicturePath().trim())){
			File srcImgFile = null;
			File destImgFile = null;
			try{
				srcImgFile = new File(ProjectConstant.APP_TEMP_IMG_FOLDER + "\\" + member.getMmbPicturePath());
				destImgFile = new File(ProjectConstant.APP_MMB_IMAGES_FOLDER + "\\" + member.getMmbPicturePath());
				FileUtils.moveFile(srcImgFile, destImgFile);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
		
		if(logger.isDebugEnabled()){
			logger.debug(o);
		}
		
		processContext.setValueObject(o);
	}


}